package com.sunwayworld.basemodule.business.pjtask.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sunwayworld.basemodule.business.pjresultedithistory.bean.LimsPjResultHistoryBean;
import com.sunwayworld.basemodule.business.pjresultedithistory.service.LimsPjResultHistoryService;
import com.sunwayworld.basemodule.business.pjtask.bean.LimsPjFolderEquipBean;
import com.sunwayworld.basemodule.business.pjtask.bean.LimsPjTaskBean;
import com.sunwayworld.basemodule.business.pjtask.computing.PjTaskComputingEngine;
import com.sunwayworld.basemodule.business.pjtask.dao.LimsPjTaskDao;
import com.sunwayworld.basemodule.business.pjtask.service.LimsPjFolderEquiptService;
import com.sunwayworld.basemodule.business.pjtask.service.LimsPjTaskService;
import com.sunwayworld.basemodule.business.result.bean.LimsResultBean;
import com.sunwayworld.basemodule.coredata.pjproduct.bean.CurrentConditionDTO;
import com.sunwayworld.framework.at.annotation.AuditTrailEntry;
import com.sunwayworld.framework.at.annotation.AuditTrailType;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.mybatis.mapper.MapperParameter;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.support.PersistableHelper;
import com.sunwayworld.framework.utils.CollectionUtils;
import com.sunwayworld.framework.utils.StringUtils;
import com.sunwayworld.module.sys.at.bean.CoreAuditTrailRecordLineBean;
import com.sunwayworld.module.sys.at.service.CoreAuditTrailRecordLineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Repository
@GikamBean
public class LimsPjTaskServiceImpl implements LimsPjTaskService {

    @Lazy
    @Autowired
    private CoreAuditTrailRecordLineService coreAuditTrailRecordLineService;

    @Lazy
    @Autowired
    private LimsPjResultHistoryService limsPjResultHistoryService;

    @Lazy
    @Autowired
    private LimsPjFolderEquiptService limsPjFolderEquiptService;

    @Autowired
    private LimsPjTaskDao limsPjTaskDao;

    @Override
    @SuppressWarnings("unchecked")
    public LimsPjTaskDao getDao() {
        return limsPjTaskDao;
    }

    @Override
    @Transactional
    @AuditTrailEntry(AuditTrailType.INSERT)
    public Long insert(RestJsonWrapperBean jsonWrapper) {
        LimsPjTaskBean limsPjTask = jsonWrapper.parseUnique(LimsPjTaskBean.class);
        limsPjTask.setId(ApplicationContextHelper.getNextIdentity());
        getDao().insert(limsPjTask);
        return limsPjTask.getId();
    }

    @Override
    public List<CurrentConditionDTO> selectCurrentConditionByTask(MapperParameter temp) {
        List<Map<String, Object>> mapList = getDao().selectCurrentConditionByTask(temp);
        if (mapList.isEmpty())
            return CollectionUtils.emptyList();
        List<CurrentConditionDTO> currentConditionDTOList = mapList.stream().map(m -> PersistableHelper.mapToPersistable(m, CurrentConditionDTO.class)).collect(Collectors.toList());
        return currentConditionDTOList;
    }

    @Override
    @Transactional
    public JSONObject updateResult(RestJsonWrapperBean wrapperBean) {
        JSONObject req = new JSONObject();
        LimsPjTaskBean taskBean = wrapperBean.parseUnique(LimsPjTaskBean.class);
        if (taskBean.getId() == null) {
            return req;
        }
        LimsPjTaskBean oldBean = this.selectByIdIfPresent(taskBean.getId());
        if (oldBean == null || oldBean.getId() == null) {
            return req;
        }
        if (StringUtils.equals(oldBean.getOriginResult(), taskBean.getOriginResult())) {
            return req;
        }
        String oldValue = oldBean.getOriginResult();
        oldBean.setOriginResult(taskBean.getOriginResult());
        oldBean.setFinalResult(taskBean.getOriginResult());
        getDao().update(oldBean, "originResult", "finalResult");

//        PjTaskComputingEngine.getEngine(Collections.singletonList(oldBean.getFolderId())).compute();
        // 公式实际取的是folderEquipId
        PjTaskComputingEngine.getEngine(Collections.singletonList(oldBean.getFolderEquipId())).compute();
        oldBean = this.selectByIdIfPresent(oldBean.getId());

        // 结果追溯记录
        CoreAuditTrailRecordLineBean coreAuditTrailRecordLineBean = new CoreAuditTrailRecordLineBean();
        coreAuditTrailRecordLineBean.setId(ApplicationContextHelper.getNextIdentity());
        coreAuditTrailRecordLineBean.setRecordId(oldBean.getFolderEquipId());
        coreAuditTrailRecordLineBean.setTableName(getDao().getTable());
        coreAuditTrailRecordLineBean.setTargetId(getDao().getTable() + "$" + oldBean.getId());
        coreAuditTrailRecordLineBean.setRecordType("UPDATE");
        coreAuditTrailRecordLineBean.setColumn("ORIGINALRESULT");
        coreAuditTrailRecordLineBean.setOldValue(oldValue);
        coreAuditTrailRecordLineBean.setNewValue(oldBean.getOriginResult());
        coreAuditTrailRecordLineService.getDao().insert(coreAuditTrailRecordLineBean);

        LimsPjResultHistoryBean historyBean = new LimsPjResultHistoryBean();
        historyBean.setId(ApplicationContextHelper.getNextIdentity());
        historyBean.setFolderId(oldBean.getFolderId());
        historyBean.setFolderEquipId(oldBean.getFolderEquipId());
        historyBean.setTaskId(oldBean.getId());
        historyBean.setOldValue(oldValue);
        historyBean.setFinalResult(oldBean.getFinalResult());
        historyBean.setUnit(oldBean.getUnit());
        historyBean.setReferTip(oldBean.getReferTip());
        historyBean.setColor(oldBean.getColor());
        historyBean.setJudge(oldBean.getJudge());
        historyBean.setResultStatus(oldBean.getResultStatus());
        limsPjResultHistoryService.getDao().insert(historyBean);

        LimsPjFolderEquipBean folderEquipBean = limsPjFolderEquiptService.selectFirstByFilter(SearchFilter.instance().match("id", oldBean.getFolderEquipId()).filter(MatchPattern.EQ));
        folderEquipBean.setResultStatus(folderEquipBean.getExt$Item("CURRENTRESULTSTATUS"));
        limsPjFolderEquiptService.getDao().update(folderEquipBean, "resultStatus");

        return req;
    }
}
